package com.ferry.transport.netty.proxy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

/**
 * Created by daiyong
 */
public class ByteBuddyProxy extends AbstractProxy {

	@Override
	public <T> T newProxy(Class<T> interfaceClass, Object handler) {
		Class<? extends T> cls = new ByteBuddy()
				.subclass(interfaceClass)
				.method(ElementMatchers.isDeclaredBy(interfaceClass))
				.intercept(MethodDelegation.to(handler, "handler"))
				.make()
				.load(interfaceClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
				.getLoaded();

		try {
			return cls.newInstance();
		} catch (Throwable t) {
			throw new RuntimeException(t);
		}
	}
}
